import React, { Component } from 'react'
import { message } from 'antd'
import { connect } from 'dva'
import { request, config } from 'utils'

// import Eloam from '../../../components/Eloam/index'
import CrossBrowserDriver from '../../../components/CrossBrowserDriver/index'
import AddNaturalPerson from './addNaturalPersonModal'
import { object, string } from 'prop-types';

const { faceHost, host, api, fileSource } = config
const { faceCompare, faceIDCompare, cardOCR, fileDeleteURL } = api

class ClientForm extends Component {
  constructor(props) {
    super(props)
    this.state = {
      people: {},
      fileList: {},
      fingerLoading: false,
      idcard00: '',
      idcard01: '',
      autographUrl: '',
      localIds: '',
      fullState: {
        assetsInfoState: 0,
        marriagestatusInfoState: 0,
        registeredResidenceInfoState: 0,
      },
      isNew: true,
    }
    this.faceType = 0
    this.pictureType = 0
    this.takeOnce = false
  }
  addThePartUser(data, deleteString) {
    this.props.dispatch({
      type: 'client/addpartyUser',
      payload: {
        data,
        deleteString
      }
    })
  }
  onUploadChange({ file, fileList, key }) {
    if (file.status == "error") {
      message.error("上传失败,请检查网络是否正常");
    }
    if (file.status == "removed") {
      if (file.response) {
        this.props.dispatch({
          type: 'client/deleteImgModels',
          payload: {
            fileId: file.response.fileId
          }
        })
      } else {
        let fileID = file.url.substring(file.url.lastIndexOf("\/") + 1, file.url.length)
        if(fileID.indexOf("?") != -1){
          let newFileID = fileID.substring(0, fileID.indexOf('?'))
          this.props.dispatch({
            type: 'client/deleteImgModels',
            payload: {
              fileId: newFileID
            }
          })
        }else{
          this.props.dispatch({
            type: 'client/deleteImgModels',
            payload: {
              fileId: fileID
            }
          })
        }
      }
    }
    const files = this.state.fileList
    if (file.status === 'done') {
      const { response } = file
      if (response.code) {
        message.error("文件上传失败:" + response.msg, 5);
        fileList[fileList.length - 1]["status"] = "error"
      }
    }
    files[key] = fileList
    this.setState({ fileList: files })
  }
  onCardOCR() {
    const { fileList } = this.state
    let idcard0 = ""
    if (fileList["5"] && fileList["5"].length > 0) {
      idcard0 = fileList["5"][fileList["5"].length - 1].url
    }
    let idcard1 = ""
    if (fileList["6"] && fileList["6"].length > 0) {
      idcard1 = fileList["6"][fileList["6"].length - 1].url
    }
    if (!idcard0 || !idcard1) {
      message.error("请先拍摄身份证正反面", 5);
      return
    }
    const s1 = idcard0.split("/")
    const s2 = idcard1.split("/")
    const fileIdStr = s1[s1.length - 1] + "#" + s2[s2.length - 1]

    const url = host + cardOCR
    const hide = message.loading('正在识别中', 0);

    request({
      url,
      data: {
        fileIdStr
      },
      method: 'POST',
    }).then(data => {

      hide()
      const { code } = data
      if (code) {
        message.error("识别失败:" + data.msg || data.message, 5)
        return
      }
      const { portrait, nationalEmblem } = data
      const address = JSON.parse(portrait["address"])["result"]
      const birthDay = JSON.parse(portrait["birth_day"])["result"]
      const birthMonth = JSON.parse(portrait["birth_month"])["result"]
      const birthYear = JSON.parse(portrait["birth_year"])["result"]
      const gender = JSON.parse(portrait["gender"])["result"]
      const idcardNumber = JSON.parse(portrait["idcard_number"])["result"]
      const name = JSON.parse(portrait["name"])["result"]
      const nationality = JSON.parse(portrait["nationality"])["result"]
      const photo = JSON.parse(portrait["portrait"])["result"]
      const issuedBy = JSON.parse(nationalEmblem["issued_by"])["result"]
      const validDateEnd = JSON.parse(nationalEmblem["valid_date_end"])["result"]
      const validDateStart = JSON.parse(nationalEmblem["valid_date_start"])["result"]

      const people = {
        name,
        sex: gender,
        nativePlace: nationality,
        dateOfBirth:
          birthYear +
          '/' +
          birthMonth +
          '/' +
          birthDay,
        address,
        cardID: idcardNumber,
        authority: issuedBy,
        validStart: validDateStart,
        validEnd: validDateEnd,
        base64: photo,
      };
      this.setState({ people })

    }).catch(e => {

      hide()
      let msg = "网络请求失败"
      if (e.message) {
        msg = JSON.parse(e.message)["msg"] || msg
      }
      message.error(msg, 5)
    })
  }
  readCard(personMessage) {
    if (!personMessage) {
      return
    } else if (typeof personMessage == 'object') {
      let people = personMessage
      this.setState({ people })
    } else if (typeof personMessage == 'string') {
      const { people } = this.state
      people.base64 = personMessage
      this.setState({ people })
    }
  }
  onFaceCheck(type) {
    this.faceType = type
    this.refs.crossBrowserDriver.openVideoMain(1, {
      // userId,
      // localId,
      // partyNumber: 0,
      // type: 0,
      // dataType: type,
      // clientUpdateAt: timestamp
    })
  }
  onSwitchChange(val, key) {
    const fullState = this.state.fullState
    if (val) {
      fullState[key] = 1
    } else {
      fullState[key] = 0
    }
    this.setState({ fullState: fullState })
  }
  readFinger() {
    this.setState({
      fingerLoading: true
    })
    this.refs.crossBrowserDriver.readFinger()

  }
  removeFinger() {
    const { people } = this.state
    people.fingerprintUrl = ""
    this.setState({ people })
  }
  onTakePicture(type, takeOnce) {
    let timestamp = new Date().getTime()
    this.pictureType = type
    this.takeOnce = takeOnce
    const localId = sessionStorage.getItem("localId")
    const userId = sessionStorage.getItem('userId')
    this.refs.crossBrowserDriver.openVideoMain(0, {
      userId,
      localId,
      partyNumber: 0,
      type: 0,
      dataType: type,
      clientUpdateAt: timestamp
    })
  }
  hiddenEdit() {
    this.props.dispatch({
      type: 'client/showDetails',
      payload: {
        showEdit: false
      }
    })
  }
  fetchFaceScore(image) {
    const { people } = this.state
    const base64 = "data:image/png;base64," + people.base64
    let url = faceHost + faceCompare
    const data = {
      "imageBase64_1": base64,
      "imageBase64_2": image,
      "idCard": people.cardID,
      "idcardName": people.name,
      "token": sessionStorage.getItem("token")
    }
    if (this.faceType === 1) {
      url = faceHost + faceIDCompare
      delete data["imageBase64_1"]
    }
    //const url="http://192.168.2.153:9000"+faceCompare
    const hide = message.loading('正在比对中', 0);
    request({
      url,
      data,
      method: 'POST',
    }).then(data => {
      hide()
      if (data.code === 0 && !data.error_message && data.confidence) {
        const { people } = this.state
        const recognitionResult = data.confidence.toFixed(2)
        people.recognitionResult = recognitionResult
        this.setState({ people })
      } else {
        alert("比对失败：" + (data.error_message || "请确保对比图片有清晰的人脸"));
      }
    }).catch(e => {
      hide()
      // 未检测到身份证头像图片
      // alert('未检测到身份证头像图片或未识别到人脸' + '')      
     let errormsg = sessionStorage.getItem('errorMessage')
     alert(errormsg)
      // alert(JSON.parse(e).description.msg + '')
    })
  }
  makeFile(files) {
    let newArry = []
    let currentTime = '?' + new Date().getTime()
    files.map((item, index) => {
      newArry.push(
        {
          uid: index,
          name: index + 'xxx.png',
          url: fileSource + item + currentTime
        }
      )
    })
    return newArry
  }
  componentDidMount() {
    //清除旧的指纹信息(可能)
    sessionStorage.removeItem("fingerImage")
    const { client, } = this.props
    const { currentInfo, isNew } = client
    // console.log(currentInfo, 'currentInfo')
    if (!isNew) {
      let currentTime = '?' + new Date().getTime()
      let recognitionResult = currentInfo.appPartyUser.recognitionResult
      sessionStorage.setItem("localId", currentInfo.appPartyUser.localId)
      let files = {}
      let fileArry0 = [currentInfo.partyFile["1"]]
      let fileArry1 = [currentInfo.partyFile["2"]]
      let fileArry2 = [currentInfo.partyFile["3"]]
      files["0"] = this.makeFile(fileArry0["0"])
      files["1"] = this.makeFile(fileArry1["0"])
      files["7"] = this.makeFile(fileArry2["0"])
      this.setState({
        people: {
          name: currentInfo.appPartyUser.name,
          address: currentInfo.appPartyUser.nativePlace,
          sex: currentInfo.appPartyUser.sex,
          dateOfBirth: currentInfo.appPartyUser.birth,
          nativePlace: currentInfo.appPartyUser.famousRace,
          address: currentInfo.appPartyUser.address,
          authority: currentInfo.appPartyUser.lssueOffice,
          validStart: currentInfo.appPartyUser.validityPeriod,
          cardID: currentInfo.appPartyUser.idCard,
          mobile: currentInfo.appPartyUser.mobile,
          email: currentInfo.appPartyUser.email,
          riskPeopleReason: currentInfo.appPartyUser.riskPeopleReason,
          riskPeople: currentInfo.appPartyUser.riskPeople,
          base64: currentInfo.appPartyUser.cardPositiveFileUrl,
          fingerprintUrl: currentInfo.appPartyUser.fingerprintUrl,
          recognitionResult: recognitionResult
        },
        idcard00: currentInfo.partyFile["5"][currentInfo.partyFile["5"].length - 1] != '' && currentInfo.partyFile["5"][currentInfo.partyFile["5"].length - 1] != undefined ? currentInfo.partyFile["5"][currentInfo.partyFile["5"].length - 1] + currentTime : '',
        idcard01: currentInfo.partyFile["6"][currentInfo.partyFile["6"].length - 1] != '' && currentInfo.partyFile["6"][currentInfo.partyFile["6"].length - 1] != undefined ? currentInfo.partyFile["6"][currentInfo.partyFile["6"].length - 1] + currentTime : '',
        fileList: files,
        fullState: {
          assetsInfoState: currentInfo.appPartyUser.assetsInfoState,
          marriagestatusInfoState: currentInfo.appPartyUser.marriagestatusInfoState,
          registeredResidenceInfoState: currentInfo.appPartyUser.registeredResidenceInfoState,
        },
        isNew: isNew
      })
    } else {
      sessionStorage.setItem("localId", new Date().getTime())
    }
  }
  resetData() {
    sessionStorage.setItem("localId", new Date().getTime())
    this.setState({
      people: {},
      fileList: {},
      fingerLoading: false,
      idcard00: '',
      idcard01: '',
      autographUrl: '',
      localIds: '',
      fullState: {
        assetsInfoState: 0,
        marriagestatusInfoState: 0,
        registeredResidenceInfoState: 0,
      }
    })
  }
  render() {
    const { location, dispatch, client, loading } = this.props
    const { showEdit, currentItem, currentInfo } = client
    const { people, fileList, fingerLoading, idcard00, idcard01, fullState, isNew, } = this.state
    // console.log(fileList,'fileList')
    const AddNaturalPersonModalProps = {
      addThePartUser: (data, deleteString) => this.addThePartUser(data, deleteString),
      onCardOCR: () => this.onCardOCR(),
      onReadFinger: () => this.readFinger(),
      onRemoveFinger: () => this.removeFinger(),
      onFaceCheck: (type) => this.onFaceCheck(type),
      onTakePicture: (type, takeOnce) => this.onTakePicture(type, takeOnce),
      onUploadChange: ({ file, fileList, key }) => this.onUploadChange({ file, fileList, key }),
      currentInfo,
      fingerLoading,
      people,
      fileList,
      showEdit,
      idcard00,
      idcard01,
      isNew,
      fullState,
      onSwitchChange: (val, key) => this.onSwitchChange(val, key),
      autographUrl: currentInfo.appPartyUser.autographUrl,
      hiddenEdit: () => this.hiddenEdit(),
      resetData: () => this.resetData(),
    }

    return (
      <div style={{ overflow: 'auto' }}>
        <AddNaturalPerson {...AddNaturalPersonModalProps} />
        <CrossBrowserDriver ref="crossBrowserDriver"
          onBiokey={(fingerData) => {
            const { people } = this.state
            people.fingerprintUrl = fingerData
            this.setState({ people, fingerLoading: false })
          }}
          onAssistPicture={(base64) => {
            this.fetchFaceScore(base64)
          }}
          readCard={(personMessage) => this.readCard(personMessage)}
          onTakePicture={(info) => {
            let a = info.json()
            a.then(obj => {
              const { fileList } = this.state
              let infoJSON = {}
              try {
                infoJSON = obj
              } catch (e) {
                message.error("服务器返回数据格式异常", 3);
                return
              }
              if (!infoJSON.fileId) {
                message.error(infoJSON.msg || "文件上传失败", 3);
                return
              }
              const url = fileSource + infoJSON.fileId
              const list = fileList[String(this.pictureType)] || []
              list.push({
                uid: new Date().getTime(),
                name: infoJSON.fileId,
                status: 'done',
                url: url
              })
              fileList[String(this.pictureType)] = list
              this.setState({
                fileList,
              })
            })
          }
          }
        />
      </div>
    )
  }
}

export default connect(({ client, loading }) => ({ client, loading }))(ClientForm)
